<?php

namespace App\Console\Commands;

use App\Models\{
    User,
    Role,
    Permission,
};
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Validation\Rules\Password;
use Illuminate\Support\Facades\Hash;

class CreateUser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user:create
                            {login : User login}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Creating user and assign them roles (by default guest)';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $validator = \Validator::make([
            'user_login' => $this->argument('login'),
            'user_full_name' => $this->ask('What is your name?'),
            'user_password' => $this->secret('Type your password'),
        ], [
            'user_login' => [
                'required',
                'max:50',
                'string',
                'unique:users',
            ],
            'user_full_name' => [
                'required',
                'max:100',
                'string',
            ],
            'user_password' => [
                'required',
                'max:100',
                Password::min(3),
            ],
        ]);

        if ($validator->fails()) {
            $this->info('User not created. See errors below:');

            foreach ($validator->errors()->all() as $error) {
                $this->error($error);
            }

            return 1;
        }

        $validated = $validator->validated();
        $user = new User([
            'user_login' => $validated['user_login'],
            'user_password' => Hash::make($validated['user_password']),
            'user_full_name' => $validated['user_full_name'],
        ]);

        $allRoles = Role::all();
        
        if (0 === $allRoles->count()) {
            $role = Role::factory()
                ->has(
                    Permission::factory()->new(['permission_name' => 'guest-view']),
                )
                ->create([
                    'role_name' => 'Guest',
                ]);
            $allRoles = new Collection([$role]);
        }

        $roles = $this->choice(
            'Which roles assign to this user?',
            $allRoles->pluck('role_name', 'role_id')->toArray(),
            $allRoles->where('role_name', 'Guest')->first()['role_id'] ?? null,
            null,
            true
        );
        $selectedRoles = $allRoles->whereIn('role_name', $roles);

        \DB::transaction(static function () use ($user, $selectedRoles) {
            $user->save();
            $user->roles()->attach($selectedRoles);
        });
        $this->info(\sprintf('User %s was created with given roles.', $user->user_full_name));

        return 0;
    }
}
